<?php
namespace App\Models;

use Encore\Admin\Traits\AdminBuilder;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\Storage;
use Encore\Admin\Auth\Database\HasPermissions;
use Illuminate\Database\Eloquent\Builder;
use App\Models\User\Profile;
use App\Models\User\Sns;
//use App\Models\Roleuser;
//use Illuminate\Support\Facades\DB;

/**
 * Class Administrator.
 *
 * @property Role[] $roles
 */
class Administrator extends Model implements AuthenticatableContract
{
    use Authenticatable, AdminBuilder, HasPermissions;

    protected $fillable = ['username', 'password', 'name', 'avatar'];

    /**
     * Create a new Eloquent model instance.
     *
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        $connection = config('admin.database.connection') ?: config('database.default');

        $this->setConnection($connection);

        $this->setTable(config('admin.database.users_table'));

        parent::__construct($attributes);
    }

    protected static function boot() {    
        parent::boot();

        static::saved(function($model) {
			if(request()->has('backend') || request()->has('roles')){
				$backends = get_backends();
				$roleModel = config('admin.database.roles_model');
				$backroles = $roleModel::whereIn('slug',$backends)->pluck('id', 'slug')->toArray(); 
				
				$backrolesids = array_values($backroles);
				
				$pivotTable = config('admin.database.role_users_table');
				
					\DB::table($pivotTable)->whereIn('role_id',$backrolesids)->where('user_id',$model->id)->delete();
					dump(\DB::table($pivotTable)->get());
					if(isset($backroles['user'])){
						\DB::table($pivotTable)->insert([
								'role_id' => $backroles['user'],
								'user_id' => $model->id,
							]);
					}
					if($model->backend!='user' && isset($backroles[$model->backend])){
						\DB::table($pivotTable)->insert([
								'role_id' => $backroles[$model->backend],
								'user_id' => $model->id,
							]);
					}
					dd(\DB::table($pivotTable)->get());

			}
        });
		/*
        $guard = config('admin.auth.guard')??'admin';
		static::addGlobalScope('avaiable',function(Builder $builder){
				//$builder->whereRaw('FIND_IN_SET(?,backend)', [$backend])->orWhere('id',1);
				//$builder->where('backend',$backend);
		});*/
    }

   

    /**
     * Get avatar attribute.
     *
     * @param string $avatar
     *
     * @return string
     */
    public function getAvatarAttribute($avatar)
    {
        if (url()->isValidUrl($avatar)) {
            return $avatar;
        }

        $disk = config('admin.upload.disk');

        if ($avatar && array_key_exists($disk, config('filesystems.disks'))) {
            return Storage::disk(config('admin.upload.disk'))->url($avatar);
        }

        $default = config('admin.default_avatar') ?: '/vendor/laravel-admin/AdminLTE/dist/img/user2-160x160.jpg';

        return admin_asset($default);
    }

    /**
     * A user has and belongs to many roles.
     *
     * @return BelongsToMany
     */
    public function roles() : BelongsToMany
    {
        $pivotTable = config('admin.database.role_users_table');

        $relatedModel = config('admin.database.roles_model');

        return $this->belongsToMany($relatedModel, $pivotTable, 'user_id', 'role_id');
    }

    /**
     * A User has and belongs to many permissions.
     *
     * @return BelongsToMany
     */
    public function permissions() : BelongsToMany
    {
        $pivotTable = config('admin.database.user_permissions_table');

        $relatedModel = config('admin.database.permissions_model');

        return $this->belongsToMany($relatedModel, $pivotTable, 'user_id', 'permission_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function profile()
    {
        return $this->hasOne(Profile::class,'user_id');
    }

    public function sns()
    {
        return $this->hasOne(Sns::class,'user_id');
    }

}
